package com.utils.httphelper;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CookieUtil {
   private static final Logger log = LoggerFactory.getLogger(CookieUtil.class);

   public static void addCookie(HttpServletRequest request, HttpServletResponse response, String key, String value, int maxage) {
      Cookie _cookie = new Cookie(key, value);
      _cookie.setMaxAge(maxage);
      _cookie.setPath("/");
      String rootDomain = request.getServerName().replaceAll(".*\\.(?=.*\\.)", "");
      _cookie.setDomain(rootDomain);
      log.info("add  cookie key:{} value:{}", key, value);
      response.addCookie(_cookie);
   }

   public static void addCookie(HttpServletResponse response, String key, String value, int maxage, String domain, String path) {
      Cookie _cookie = new Cookie(key, value);
      _cookie.setMaxAge(maxage);
      _cookie.setPath(path);
      _cookie.setDomain(domain);
      log.info("add  cookie key:{} value:{}", key, value);
      response.addCookie(_cookie);
   }

   public static String getCookie(HttpServletRequest request, String key) {
      try {
         Cookie[] e = request.getCookies();
         if(e != null) {
            Cookie[] arg2 = e;
            int arg3 = e.length;

            for(int arg4 = 0; arg4 < arg3; ++arg4) {
               Cookie _cookie = arg2[arg4];
               if(_cookie.getName().equalsIgnoreCase(key)) {
                  log.info("get cookie name:{} value:{}", key, _cookie.getValue());
                  return _cookie.getValue();
               }
            }
         }
      } catch (Exception arg6) {
         arg6.printStackTrace();
      }

      log.info("not found cookie for name:{} ", key);
      return null;
   }

   public static void main(String[] args) {
   }
}